<style lang="scss" scoped>
.delete-button {
  height: 100%;
}
</style>
<template>
  <!--  对场景做判断,如果是0代表编辑地址页面,如果是1代表新增地址页面-->
  <van-nav-bar
    :title="scene === 0 ? '我的地址' : '编辑地址'"
    left-arrow
    left-text="返回"
    @click-left="scene === 0 ? $router.back() : click_left()"
  />
  <div class="main">
    <div v-if="scene === 0">
      <van-address-list
        v-model="order_store.addr_id"
        :list="format_user_address"
        default-tag-text="默认"
        @add="address_list_on_add"
        @edit="address_list_on_edit"
        @select="select_address"
      />
    </div>

    <div v-if="scene === 1">
      <van-form label-width="150px" @submit="add_or_update_address">
        <van-cell-group>
          <van-field
            v-model="add_or_edit_address_form.name"
            :rules="[{ required: true, message: '请填写收货人' }]"
            label="收货人"
            name="收货人"
            placeholder="请填写收货人"
          />
          <van-field
            v-model="add_or_edit_address_form.phone"
            :rules="[{ required: true, message: '请填写电话号码' }]"
            label="电话号码"
            name="电话号码"
            placeholder="请填写电话号码"
          />

          <!-- 省市区选择器       -->
          <van-field
            v-model="cascader_selection"
            is-link
            label="地区"
            placeholder="请选择所在地区"
            readonly
            @click="show_cascader = true"
          />
          <van-popup v-model:show="show_cascader" position="bottom" round>
            <van-cascader
              v-model="add_or_edit_address_form.area"
              :field-names="field_names"
              :options="city_list"
              title="请选择所在地区"
              @close="show_cascader = false"
              @finish="cascader_finish"
            />
          </van-popup>

          <van-field
            v-model="add_or_edit_address_form.desc"
            :rules="[{ required: true, message: '请填写详细地址' }]"
            autosize
            label="详细地址"
            placeholder="请输入详细地址"
            rows="1"
            type="textarea"
          />
          <van-field
            v-if="show_default_address_switch"
            label="是否设置为默认地址"
            name="switch"
          >
            <!--设置默认地址框,v-model表示是否发送设置默认地址的请求-->
            <template #input>
              <van-switch v-model="set_default" />
            </template>
          </van-field>
        </van-cell-group>
        <div style="margin: 16px">
          <van-button block native-type="submit" round type="primary">
            提交
          </van-button>
        </div>
        <div style="margin: 16px">
          <van-button
            v-if="show_default_address_switch"
            block
            round
            type="danger"
            @click="delete_address"
          >
            删除地址
          </van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive, watch, computed } from "vue";
import { showNotify, showToast } from "vant";
import { useRouter } from "vue-router";
import {
  api_get_all_city,
  api_add_or_update_address,
  api_get_user_address,
  api_set_default_address,
  api_delete_address,
} from "@/service/api/address";

import { use_order_store } from "@/stores/order-store";
import { format_address } from "@/utils/format-user-address";
// 引入仓库
const order_store = use_order_store();
// 引入路由
const $router = useRouter();
// 初始化场景,0代表是编辑地址页面,1代表是新增/修改地址页面
const scene = ref(0);

/*
 *
 * 地址展示页面
 *
 * */
// 获取所有的用户地址信息
const user_address = ref([]);
const get_user_address = async () => {
  let res: any = await api_get_user_address();
  user_address.value = res.result;
  console.log(res);
};
// 获取所有的城市列表
const city_list = ref([]);
const get_all_city = async () => {
  let res: any = await api_get_all_city();
  city_list.value = res.result;
};

//对用户信息等进行格式化
const format_user_address = computed(() => {
  return user_address.value.map((address: any) => {
    return {
      id: address.id,
      name: address.name,
      tel: address.phone,
      address: `${format_address(address.area, city_list.value)} ${
        address.desc
      }`,
      isDefault: address.default_set === 1 ? true : false,
    };
  });
});
/*
 *
 * 地址展示页面结束
 *
 * */

/*
 *
 * 地址修改页面
 *
 * */
// 控制是否展示设置默认地址栏
const show_default_address_switch = computed(() => {
  return !!add_or_edit_address_form.value.id;
});
// 选择地址事件时的回调
const select_address = (item) => {
  order_store.address_info = item;
};
// 初始化是否设置默认地址的开关,如果此项为真,则在保存时发送设置默认地址的请求
const set_default = ref(false);
// 控制级联选择器显示/隐藏
let show_cascader = ref(false);
// 级联多选器选择结果
let cascader_selection = ref("");
// 级联多选器的显示设置
let field_names = {
  text: "cityname",
  value: "id",
  children: "children",
};
// 添加地址的请求表单
let add_or_edit_address_form = ref({
  name: "",
  phone: "",
  area: "",
  desc: "",
});
// 级联选择器的确认后回调函数
const cascader_finish = ({ selectedOptions }) => {
  show_cascader.value = false;
  console.log(selectedOptions);
  cascader_selection.value = selectedOptions
    .map((option) => option.label)
    .join("/");
  add_or_edit_address_form.value.area = selectedOptions
    .map((option) => option.value)
    .join(",");
};

interface city_item {
  cityname: string;
  id: number | string;
  key: number;
  label: string;
  pid: number;
  type: number;
  value: number;
  children?: city_item[];
}

// 初始化表单的函数
const init_address_form = () => {
  cascader_selection.value = "";
  Object.assign(add_or_edit_address_form.value, {
    id: "",
    name: "",
    phone: "",
    area: "",
    desc: "",
  });
};
//发送更新/添加请求的函数
const add_or_update_address = async () => {
  // 如果选了省市区才发送请求
  if (!cascader_selection.value) {
    showNotify({
      type: "danger",
      message: "请选择省市区!",
    });
    return;
  } else {
    if (!!set_default.value) {
      let res = await api_set_default_address(
        add_or_edit_address_form.value.id,
      );
      set_default.value = false;
    }
    let res: any = await api_add_or_update_address(
      add_or_edit_address_form.value,
    );
    if (res.msg) {
      showToast(res.msg);
    }
    scene.value = 0;
    await get_user_address();
    init_address_form();
  }
};
onMounted(async () => {
  await get_all_city();
  await get_user_address();
});

// // 选择的订单地址id
// const chosenAddressId = ref("1");

// 点击返回按钮时,清空编辑表格的对象
const click_left = () => {
  scene.value = 0;
  init_address_form();
};

const address_list_on_add = () => {
  scene.value = 1;
};
const address_list_on_edit = (_, index) => {
  scene.value = 1;
  Object.assign(add_or_edit_address_form.value, user_address.value[index]);
};

const delete_address = async () => {
  let res = await api_delete_address(add_or_edit_address_form.value.id);
  showToast(res.msg);
  scene.value = 0;
  get_user_address();
};
/*
 *
 * 地址修改页面结束
 *
 * */
</script>
